package com.common.project.util;

import com.common.project.common.StatusCode;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @ClassName Response
 * @Description
 * @Author jiangshicun@bicai365.com
 * @Date 2019/6/20 13:59
 */
public class Response <T> implements DTO {
    private boolean isSuccess;
    private String code;
    private String message;
    private T data;

    public static Response success() {
        Response response = new Response();
        response.setSuccess(true);
        return response;
    }

    public static <T> Response<T> success(T data) {
        Response<T> response = new Response();
        response.setSuccess(true);
        response.setData(data);
        return response;
    }

    public static Response failure() {
        Response response = new Response();
        response.setSuccess(false);
        return response;
    }

    public static Response failure(StatusCode errorCode) {
        Response response = new Response();
        response.setSuccess(false);
        response.setCode(errorCode.getCode());
        String value = I18nUtil.getString(errorCode.getCode());
        response.setMessage(StringUtils.isNotEmpty(value) ? value : errorCode.getMessage());
        return response;
    }

    public static String getServerIp() {
        String server_ip = null;

        try {
            Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();

            while(netInterfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface)netInterfaces.nextElement();
                Enumeration addresses = ni.getInetAddresses();

                while(addresses.hasMoreElements()) {
                    InetAddress ip = (InetAddress)addresses.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(58) == -1) {
                        server_ip = ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException socketException) {
            server_ip = null;
            socketException.printStackTrace();
        }

        return server_ip;
    }

    public boolean isSuccess() {
        return this.isSuccess;
    }

    public String getCode() {
        return this.code;
    }

    public String getMessage() {
        return this.message;
    }

    public T getData() {
        return this.data;
    }

    public void setSuccess(boolean isSuccess) {
        this.isSuccess = isSuccess;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Response() {
    }
}
